package org.swxjava.util;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.swxjava.Call;
import org.swxjava.Container;
import org.swxjava.core.ServiceLocatorManager;
import org.swxjava.locator.ServiceLocator;

public class RequestUtils {

	public static final String PARAM_SERVICE_CLASS = "serviceClass";
	public static final String PARAM_METHOD = "method";
	public static final String PARAM_ARGS = "args";
	public static final String PARAM_URL = "url";
	public static final String PARAM_DEBUG = "debug";
	
	public static final Call createCall(HttpServletRequest req, Container container) throws InstantiationException {
		// mandatory parameters
		String serviceClass = req.getParameter(PARAM_SERVICE_CLASS);
		String method = req.getParameter(PARAM_METHOD);
		// option parameters
		String args = req.getParameter(PARAM_ARGS);
		String url = req.getParameter(PARAM_URL);
		String debug = req.getParameter(PARAM_DEBUG);
		
		if(StringUtils.isBlank(serviceClass)) {
			throw new IllegalArgumentException("Parameter[serviceClass] can not be null.");
		}
		if(StringUtils.isBlank(method)) {
			throw new IllegalArgumentException("Parameter[method] can not be null.");
		}
		
		//container.getBea
		Call call = new Call();
		call.setServiceClass(serviceClass);
		call.setMethodName(method);
		call.setArgs(args);
		call.setUrl(url);
		call.setDebug(debug);

		// set service instance from service locator
		ServiceLocator locator = findServiceLocatorFromContainer(serviceClass, container);
		if(locator == null) {
			throw new IllegalArgumentException("Could not find any service named : " + serviceClass);
		}
		call.setServiceInstance(locator.getInstance());
		
		return call;
	}
	
	protected static ServiceLocator findServiceLocatorFromContainer(String serviceName, Container container)  {
		ServiceLocatorManager locatorManager = container.getServiceLocatorManager();
		return locatorManager.getServiceLocator(serviceName);
	}
	
	public static final String createUrl(HttpServletRequest req) {
		StringBuffer sb = new StringBuffer();
		sb.append("[").append(req.getMethod()).append("] ");
		sb.append(req.getRequestURL()).append("?");
		if("POST".equalsIgnoreCase(req.getMethod())) {
			sb.append(debugRequestParameters(req));
		} else {
			sb.append(req.getQueryString());
		}
		return sb.toString();
	}
	
	public static final String debugRequestParameters(HttpServletRequest req) {
		StringBuffer sb = new StringBuffer();
		for(Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
			String paramName = e.nextElement();
			String paramValue = req.getParameter(paramName);
			sb.append(paramName + "=" + paramValue);
			if(e.hasMoreElements()) {
				sb.append("&");
			}
		}
		return sb.toString();
	}
}
